package net.qhzw.vip.qiyu.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.HashMap;
import java.util.Map;

/**
 * 维修订单
 */
@SpringBootConfiguration
public class HallOrderTtlQueueConfig {

    //普通交换机的名称
    public final static String HALL_ORDER_EXCHANGE = "HALL_ORDER_EXCHANGE";
    //死信交换机的名称
    public final static String HALL_ORDER_DEAD_LETTER_EXCHANGE = "HALL_ORDER_DEAD_LETTER_EXCHANGE";
    //普通队列的名称
    public final static String QUEUE_HALL_ORDER = "QUEUE_HALL_ORDER";
    //死信队列的名称
    public final static String DEAD_LETTER_QUEUE_HALL_ORDER = "DEAD_LETTER_QUEUE_HALL_ORDER";

    //声明交换机
    @Bean("hallOrderExchange")
    public DirectExchange hallOrderExchange() {
        return new DirectExchange(HALL_ORDER_EXCHANGE);
    }

    //声明交换机
    @Bean("hallOrderDeadLetterExchange")
    public DirectExchange hallOrderDeadLetterExchange() {
        return new DirectExchange(HALL_ORDER_DEAD_LETTER_EXCHANGE);
    }

    //声明普通队列 TTL
    @Bean("queueHallOrder")
    public Queue queueHallOrder() {
        //正常队列绑定死信交换机信息，因为正常队列消息会变为死信
        Map<String, Object> arguments = new HashMap<>(3);
        //正常队列设置死信交换机 参数 key 是固定值
        arguments.put("x-dead-letter-exchange", HALL_ORDER_DEAD_LETTER_EXCHANGE);
        //正常队列设置死信 routing-key 参数 key 是固定值
        arguments.put("x-dead-letter-routing-key", "HALL_ORDER");
        //设置过期时间 10s,单位是ms，可以在消费者正常队列处设置，也可以在生产者发送处设置
        arguments.put("x-message-ttl", 1000 * 60 * 15);
        return QueueBuilder.durable(QUEUE_HALL_ORDER).withArguments(arguments).build();
    }

    //声明死信队列
    @Bean("deadLetterQueueHallOrder")
    public Queue deadLetterQueueHallOrder() {
        //没有参数
        return QueueBuilder.durable(DEAD_LETTER_QUEUE_HALL_ORDER).build();
    }

    //五大组件完毕，开始互相绑定
    @Bean
    public Binding queueHallOrderBindingHallOrderExchange(@Qualifier("queueHallOrder") Queue queueHallOrder,
                                                          @Qualifier("hallOrderExchange") DirectExchange hallOrderExchange) {
        //将 X 正常交换机和 QA 队列 绑定
        return BindingBuilder.bind(queueHallOrder).to(hallOrderExchange).with("hallOrder");
    }

    @Bean
    public Binding deadLetterQueueHallOrderBindingHallOrderDeadLetterExchange(@Qualifier("deadLetterQueueHallOrder") Queue deadLetterQueueHallOrder,
                                                                              @Qualifier("hallOrderDeadLetterExchange") DirectExchange hallOrderDeadLetterExchange) {
        //将 Y 死信交换机和 QD 死信队列 绑定
        return BindingBuilder.bind(deadLetterQueueHallOrder).to(hallOrderDeadLetterExchange).with("HALL_ORDER");
    }

}
